
<template>
  <Card>
    <template #title>
      <div class="flex justify-content-between">
        <!-- @vue-ignore -->
        <Button label="新增" icon="pi pi-plus" iconPos="right" @click="dialogRef?.openDialog()" />
        <span class="p-input-icon-left flex">
          <i class="pi pi-search z-1" />
          <InputText v-model="filterBusinessKey" placeholder="请输入调用方key" />
        </span>
      </div>
    </template>
    <template #content>
      <!-- ! lazy 模式下 totalRecords 才能生效 -->
      <DataTable paginator @page="onPageChange" :rows="pageSize" :totalRecords="total"
        :rowsPerPageOptions="[5, 10, 20, 50]" lazy :loading="loading" :value="data" data-key="id"
        tableStyle="min-width: 50rem" columnResizeMode="expand">
        <Column field="id" header="ID" class="w-5rem"></Column>
        <Column field="businessKey" header="调用人" class="w-8rem"></Column>
        <Column field="businessDeveloper" header="对接人" class="w-8rem"></Column>
        <Column field="createAt" header="创建日期">
          <template #body="slotProps">
            {{ dayjs(slotProps.data.createAt).format('YYYY/MM/DD HH:mm:ss') }}
          </template>
        </Column>
        <Column field="updatedAt" header="更新日期">
          <template #body="slotProps">
            {{ dayjs(slotProps.data.updatedAt).format('YYYY/MM/DD HH:mm:ss') }}
          </template>
        </Column>
        <Column field="isUsed" header="可用状态" class="w-8rem">
          <template #body="slotProps">
            <Tag :value="slotProps.data.isUsed == 1 ? '启用' : '禁用'" :severity="slotProps.data.isUsed == 1 ? 'success' : 'warning'" />
          </template>
        </Column>
        <Column field="operator" header="操作" class="w-14rem">
          <template #body="slotProps">
            <SplitButton label="详情" icon="pi pi-plus" raised size="small" @click="detail(slotProps.data)"
              :model="btnItems(slotProps.data)" />
          </template>
        </Column>
      </DataTable>
    </template>
  </Card>
  <Dialog v-model:visible="detailDialogVisible" modal header="查看详情" :style="{ width: '26vw' }">
    <p>调用方 KEY ：{{ detailDialog?.businessKey }}</p>
    <p>调用方 SECRET ：{{ detailDialog?.businessSecret }}</p>
    <p>备注：{{ detailDialog?.remark }}</p>
  </Dialog>
  <AddAdmin ref="dialogRef" @reload="reload"/>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue';
import { } from 'primevue/api'
import dayjs from 'dayjs';
import { usePagination } from '@alova/scene-vue'
import { useToast } from 'vue-toastification'
import { DataTable, Column, Card, Button, Tag, SplitButton, InputText, Dialog } from '@/utils/primevue'
import { useAuthorizedStore } from '@/stores/authorized';
import AddAdmin from './components/AddAdmin.vue';
import { queryAuthList } from '@/api/authorized';
import type{ TAuthorizedItem } from '@/typing/authorized';
import { useRouter } from 'vue-router';

const toast = useToast()
const authorizedStore = useAuthorizedStore()
const dialogRef = ref(undefined)
// @ts-ignore
const detailDialog = ref<TAuthorizedItem>()
const detailDialogVisible = ref(false)
const filterBusinessKey = ref<string>('')
const router = useRouter()

const btnItems = (props: TAuthorizedItem) => {
  return [
    {
      label: props.isUsed == 1 ? '禁用' : '启用',
      icon: 'pi pi-unlock',
      command: async () => {
        console.log('禁用', props)
        authorizedStore.disabledAuthorized({
          id: props.id,
          used: props.isUsed == 1 ? -1 : 1
        }, () => {
          toast.success("禁用/启用成功！");
          refresh()
        })
      }
    },
    {
      label: '接口',
      icon: 'pi pi-sliders-h',
      command: () => {
        router.push({
          path: "/authorized/authorized-action/" + props.businessKey,
          query: {
            name: props.businessKey
          }
        });
      }
    },
    {
      label: '删除', icon: 'pi pi-power-off', command: async () => {
        authorizedStore.deleteAuthorized({
          id: props.id,
        }, () => {
          toast.success("删除成功！");
          reload()
        })
      }
    }
  ]
};

const {
  // 重置表格数据，请求第一页
  reload,
  refresh,
  // 加载状态
  loading,
  // 列表数据
  data,
  // 当前页码，改变此页码将自动触发请求
  page,
  // 每页数据条数
  pageSize,
  // 总数据量
  total
} = usePagination(
  // Method实例获取函数，它将接收page和pageSize，并返回一个Method实例
  (page, pageSize) => queryAuthList({ page: page, pageSize, businessKey: filterBusinessKey.value, businessDeveloper: '' }),
  {
    preloadPreviousPage: false, // 关闭预加载上一页数据
    preloadNextPage: false, // 关闭预加载下一页数据
    total: (res: any) => res.data.total,
    data: (res: any) => res.data.authList as TAuthorizedItem[],
    // 请求前的初始数据（接口返回的数据格式）
    initialData: { total: 0, data: [] },
    initialPage: 1, // 初始页码，默认为1
    initialPageSize: 10, // 初始每页数据条数，默认为10
    watchingStates: [filterBusinessKey],
    debounce: 500
  }
);

// 页码改变的事件处理函数
const onPageChange = (event: any) => {
  page.value = event.page + 1
  pageSize.value = event.rows
}

const detail = (props: TAuthorizedItem) => {
  detailDialog.value = props
  detailDialogVisible.value = true
}

</script>
